package lib;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

import play.db.DB;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JExcelApiExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRRtfExporter;
import net.sf.jasperreports.engine.export.JRTextExporter;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.view.JasperViewer;

public class BaseJasperReport {
  //here should be jrxml and jasper files, 
  //you can generate them with iReports(I'm using netbeans plugin)
  // http://jasperforge.org/projects/ireport 
  static String REPORT_DEFINITION_PATH = "./app/views/jasper/";
  static JRExporter  exporter;
  
  public static InputStream generateReport(String reportDefFile, Map reportParams,String ext) {
    OutputStream os = new ByteArrayOutputStream();
    try {
      String compiledFile = REPORT_DEFINITION_PATH + reportDefFile + ".jasper";
      JasperCompileManager.compileReportToFile(REPORT_DEFINITION_PATH + reportDefFile + ".jrxml", compiledFile);
      JasperPrint jrprint = JasperFillManager.fillReport(compiledFile, reportParams, DB.getConnection());
      
      if (ext.equalsIgnoreCase("pdf"))
      {
    	  exporter = new JRPdfExporter();
      }else if (ext.equalsIgnoreCase("xls")){
    	  exporter = new JExcelApiExporter();
         
      }else if (ext.equalsIgnoreCase("rtf")) {
    	  exporter = new JRRtfExporter();
      }else if (ext.equalsIgnoreCase("html")) {
    	  exporter = new JRHtmlExporter();
    	  exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, false);
      }

      exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os);
      exporter.setParameter(JRExporterParameter.JASPER_PRINT, jrprint);
      exporter.exportReport();
      
    } catch (Exception e) {
      e.printStackTrace();
    }
    return new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray());
  }
}